/**
 * @program: clms-second
 * @description: 阿里沙箱支付工具类
 * @author: mitu_echo
 * @create: 2021-08-02 14:19
 **/

package com.second.alipay.pojo.utils;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.domain.AlipayTradePrecreateModel;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.api.request.AlipayTradePrecreateRequest;
import com.alipay.api.request.AlipayTradeQueryRequest;
import com.alipay.api.response.AlipayTradePrecreateResponse;
import com.alipay.api.response.AlipayTradeQueryResponse;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.HashMap;
import java.util.Map;

public class AlipayUtils {

    /**
     * 第一个参数是 阿里支付的网关
     * 第二个参数是 APPID
     * 第三个参数是 私钥
     * 第四个参数是 格式
     * 第五个参数是 支付宝公钥
     * 第六个参数是 秘钥类型
     */
    private static AlipayClient alipayClient = new DefaultAlipayClient(
            "https://openapi.alipaydev.com/gateway.do",
            "2021000117697588",
            "MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQCTwBMVq7j52FJxxjJsRBzePNvnanZAHP92goY07gSt8ew/Zz7hwTLZ9p+FXmTmEdTd3NHFhC/+CjyxxzE5u6gzKjr3+i/pgQ4R+urUQ3B2EOlNHNabXOcgdedLy+wXDpW3/DVLOAawfvTYGVwDKAaSXysrfncLinuj4aD9tSwz27yxa4opfFpcR9KsAtUITVwBCtrdmv2uRAtX+cW4asv8V1JJ7z27nfTGD/QIjZiKsQn61uZCXkCwasJHNkiNDp8baRfzeKic1i4P1daC53pyWkSzu20OOiU2F3z9HM1UfwaeSMS5Cc/1sb+n84vbAc/Qp1AftPnqoNIUxsQ2qRKPAgMBAAECggEAWyLqYr6m/e4ShL2VkrS8/dSabHd983QvnAFNGU8MMeN9L2rXHdfXLx1yLokYQdYT8Lpp5qTwGYpk/9/3nD4FtXHCJ/36GdWSQUL+IOpsb1dlITy9n93Bb4NqpZVmz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dMap+aI9oAJA=",
            "json","utf-8",
            "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAreEyGOyJfCq9nMwS+yQHWM5C7UJo9wtX2OR6Rw+o5iZ681qMJ1agWFHj3XsJ9F9VUMHfH5WCPqGqAxlO6SfzHA4GgA3Hu5XQd7TFPGJ2JyP1bjMpKirzgNmNVCdKPmelNXAekAfw27K4xtxkDoBuKdyCWvET2trObig2NyGOPV6YmrQCEwUB6b1SWzPzcG/0sHGa86GMhdinEpIkJ9vDlRE43ogntTDmDecC+UEKAwKxGRr0gnDghd7lojCjrAmayYGPQiqxRsBxbRM2qxMKkD1tTRk4AFythkTeSF2/AC936g5NO7k+4jx/nQ4rUI+1Cq4ngUTm9pJC5Agwry2ruwIDAQAB",
            "RSA2"
    );

    public static String doPay(String orderId,String orderMoney) throws UnsupportedEncodingException {
        // 订单号
        String out_trade_no = orderId;
        out_trade_no = URLDecoder.decode(out_trade_no,"UTF-8");
        // 支付金额
        String total_amount = orderMoney;
        total_amount = URLDecoder.decode(total_amount,"UTF-8");
        // 标题
        String subject = "迷途的黑店";
        subject = URLDecoder.decode(subject,"UTF-8");
        // 描述
        String body = "正在给迷途的黑店付款";
        body = URLDecoder.decode(body,"UTF-8");
        // 创建API对应的request
        AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
        // 同步通知，支付成功的通知页面，如果使用了，自定义二维码，就不会进入这个方法
        alipayRequest.setReturnUrl("http://9auety.natappfree.cc/clms-alipay/alipay/returnUrl");
        // 异步通知，支付成功后，支付宝的回调地址
        alipayRequest.setNotifyUrl("http://9auety.natappfree.cc/clms-alipay/alipay/notifyUrl");
        // 配置参数，填充业务参数
        alipayRequest.setBizContent("{" +
                "    \"out_trade_no\":\""+ out_trade_no +"\"," +
                "    \"product_code\":\"FAST_INSTANT_TRADE_PAY\"," +
                "    \"total_amount\":"+ total_amount +"," +
                "    \"subject\":\""+ subject +"\"," +
                "    \"body\":\""+ body +"\"" +
                "    }"+
                "  }");
        String form="";
        try {
            // 调用SDK生成表单
            form = alipayClient.pageExecute(alipayRequest).getBody();
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        // form就是一个表单 html 直接给前端 替换 body标签里面的东西
        return form;
    }

    /**
     * 查询支付宝订单状态的方法
     * @param orderId
     * @return
     */
    public static Map<String, String> getAliPayStatus(String orderId) throws AlipayApiException {

        AlipayTradeQueryRequest request = new AlipayTradeQueryRequest();
        request.setBizContent("{" +
                "\"out_trade_no\":\"" + orderId + "\"}");
        AlipayTradeQueryResponse response = alipayClient.execute(request);
        System.out.println(response.toString());
        HashMap<String, String> map = new HashMap<>();
        if (response.isSuccess()) {
            // 判断支付宝是否成功
            if (response.getTradeStatus().equals("TRADE_SUCCESS")) {
                map.put("payType", "SUCCESS");
            } else {
                map.put("payType", "ERROR");
            }
        } else {
            map.put("payType", "REPERROR");
        }
        return map;
    }

    /**
     * 获取支付二维码，不使用支付宝默认的跳转连接
     * @param orderId 订单号
     * @param orderMoney 支付金额
     * @return code 支付宝自定义的二维码
     * @throws Exception
     */
    public static String getCode(String orderId,String orderMoney) throws Exception{

        //---------------------------------------
        //------AlipayTradePrecreateModel--------
        //---------------------------------------
        AlipayTradePrecreateModel model = new AlipayTradePrecreateModel();
        // 订单号
        model.setOutTradeNo(orderId);
        // 标题
        model.setSubject("迷途的黑店");
        // 支付金额
        model.setTotalAmount(orderMoney);
        // 该笔订单允许的最晚付款时间，逾期将关闭交易
        model.setTimeoutExpress("1m");
        //----------------------------------------
        //-----AlipayTradePagePayRequest----------
        //----------------------------------------
        AlipayTradePrecreateRequest request = new AlipayTradePrecreateRequest();
        request.setBizModel(model);
        // 支付宝支付成功后，异步调用的方法
        request.setNotifyUrl("http://vm459u.natappfree.cc/clms-alipay/alipay/notifyUrl");
        AlipayTradePrecreateResponse response = alipayClient.execute(request);
        if (response.isSuccess()) {
            // 自定义生成的二维码路径
            String code = response.getQrCode();
            System.out.println("code:"+code);
            return code;
        } else {
            throw new RuntimeException("支付宝生成二维码失败");
        }
    }
}
